#include "Flag1Status.h"
#include <QDebug>

Flag1Status::Flag1Status(const QJsonObject &statusDetails, QWidget *parent)
    : QWidget(parent)
{
    flagLimit = false;
    setupControlLayout(statusDetails);  // 设置控件的布局
}


void Flag1Status::setupControlLayout(const QJsonObject &statusDetails)
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setAlignment(Qt::AlignTop);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    QString labelText = statusDetails.value("label1").toString();
    QString lineEditName = statusDetails.value("lineedit").toString();

    // ===== 创建 rowWidget =====
    QWidget *rowWidget = new QWidget(this);
    rowWidget->setStyleSheet(R"(
        QWidget {
            background-color: #22314a;
            border-radius: 6px;
            padding: 4px 4px;
        }
    )");

    rowWidget->setFixedWidth(400);

    QHBoxLayout *rowLayout = new QHBoxLayout(rowWidget);
    rowLayout->setContentsMargins(6, 2, 6, 2);
    rowLayout->setSpacing(10);

    // 图标
    QLabel *iconLabel = new QLabel(rowWidget);
    iconLabel->setPixmap(QIcon(":/img/fa-cog.png").pixmap(20, 20));
    rowLayout->addWidget(iconLabel);

    // 标签
    QLabel *label = new QLabel(labelText, rowWidget);
    label->setStyleSheet(R"(
        QLabel {
            font-size: 20px;
            color: #94a3b8;
        }
    )");
    rowLayout->addWidget(label);

    // 数值框
    QLineEdit *lineEdit = new QLineEdit(rowWidget);
    lineEdit->setObjectName(lineEditName);
    lineEdit->setReadOnly(true);
    lineEdit->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    lineEdit->setStyleSheet(R"(
        QLineEdit {
            background: transparent;
            border: none;
            color: white;
            font-size: 20px;
            font-weight: bold;
        }
    )");
    rowLayout->addWidget(lineEdit);

    // 单位标签
    QLabel *unitLabel = new QLabel(u8"°", rowWidget);
    unitLabel->setStyleSheet(R"(
        QLabel {
            font-size: 20px;
            font-weight: bold;
            color: white;
        }
    )");
    rowLayout->addWidget(unitLabel);

    // 存储 QLineEdit
    fieldLineEdits.insert(lineEditName, lineEdit);

    // ===== 创建外部居中布局：左右弹簧夹 rowWidget =====
    QWidget *outerWidget = new QWidget(this);
    QHBoxLayout *outerLayout = new QHBoxLayout(outerWidget);
    outerLayout->setContentsMargins(0, 0, 0, 0);
    outerLayout->addStretch();             // 左弹簧
    outerLayout->addWidget(rowWidget);     // 居中的 row
    outerLayout->addStretch();             // 右弹簧

    mainLayout->addWidget(outerWidget);
}


void Flag1Status::updateFieldValue(const QString &fieldName, const QString &newValue)
{
    if (fieldLineEdits.contains(fieldName)) {
        fieldLineEdits[fieldName]->setText(newValue);  // 更新 QLineEdit 的值
    } else {
        //qWarning() << "Field name not found: " << fieldName;
    }
}


void Flag1Status::attachToNode(QSharedPointer<DeviceNode> node)
{
    if (m_node) {
        disconnect(m_node.data(), &DeviceNode::cmdReceived,
                   this, &Flag1Status::onDataReceived);
        disconnect(m_node.data(), &DeviceNode::eventReceived,
                   this, &Flag1Status::onEventReceived);
    }
    m_node = node;
    if (m_node) {
        connect(m_node.data(), &DeviceNode::cmdReceived,
                this, &Flag1Status::onDataReceived);
        connect(m_node.data(), &DeviceNode::eventReceived,
                this, &Flag1Status::onEventReceived);
    }
}

void Flag1Status::onEventReceived(const QString& content)
{
    //m_eventLabel->setText("Event: " + content);
    //qDebug()<<"Flag1Status Received Event "<<content<<Qt::endl;
    subEventCallBack(content);
}

void Flag1Status::onDataReceived(const QString &content)
{
    if(flagLimit)
    {
        dataAnayle(content);
        flagLimit = false;
    }
    else
        flagLimit = true;
}


void Flag1Status::dataAnayle(const QString& content)
{
    //qDebug() << "Flag1Status Node Received Statu " << content << Qt::endl;

    // 解析JSON字符串
    QJsonDocument doc = QJsonDocument::fromJson(content.toUtf8());

    // 判断是否成功解析
    if (doc.isObject()) {
        QJsonObject obj = doc.object();

        // 遍历JSON对象的所有键值对
        QJsonObject::const_iterator iter = obj.constBegin();
        QString key;
        QJsonValue value;
        QString valueF;
        while (iter != obj.constEnd()) {
            // 打印每个键和值
            key = iter.key();
            value = iter.value();
            valueF = " ";
            // 根据值的类型
            if(value.isArray())
            {
                QJsonArray jsonArray = value.toArray();
                int i=1;
                QString nameX;
                for (const auto &value : jsonArray) {
                    //nameArray.push_back(value.toDouble());
                    valueF = QString::number(value.toDouble());
                    nameX = key+QString::number(i);

                    QMetaObject::invokeMethod(this, [this, nameX, valueF]() {
                        updateFieldValue(nameX, valueF);
                    }, Qt::QueuedConnection);
                    i++;
                }
                ++iter;
                continue;
            }

            if (value.isDouble()) {
                //qDebug() << key << ": " << value.toDouble();
                valueF = QString::number(value.toDouble());
            } else if (value.isBool()) {

                valueF = value.toBool() ? "TRUE" : "FALSE";
            } else if (value.isString()) {
                //qDebug() << key << ": " << value.toString();
                valueF = value.toString();
            } else {
                qDebug() << key << ": unknown type";
            }

            QMetaObject::invokeMethod(this, [this, key, valueF]() {
                updateFieldValue(key, valueF);
            }, Qt::QueuedConnection);

            // 前进到下一个键值对
            ++iter;
        }
    } else {
        qDebug() << "Failed to parse JSON." << Qt::endl;
    }
}

void Flag1Status::subEventCallBack(const QString& content)
{

}
